//TCP Socket服务
package socket

import (
	"log"
	"net"
	"os"
	"strconv"
)

//检测错误
func noError(err error) bool {
	if err != nil {
		Log(err)
		return false
	}
	return true
}

//开启服务
func ServerStart(port int) {
	go func() {
		tcpaddress, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port))
		if err != nil {
			Log("监听地址转换失败")
		}
		nListen, err := net.ListenTCP("tcp", tcpaddress)
		if !noError(err) {
			Log("端口监听失败")
			os.Exit(1)
		}
		defer nListen.Close()
		Log("监听服务开启:", port)
		for {
			conn, err := nListen.Accept()
			if !noError(err) {
				continue
			}
			go handleConnection(conn)
		}
	}()
}

func handleConnection(conn net.Conn) {
	defer conn.Close()
	// 缓冲区，存储被截断的数据
	tmpBuffer := make([]byte, 0)
	//接收解包
	readerChannel := make(chan Msg, 16)
	go reader(readerChannel)
	buffer := make([]byte, 2048)
	for {
		n, err := conn.Read(buffer)
		if err != nil {
			Log(conn.RemoteAddr().String(), " connection error: ", err)
			return
		}
		tmpBuffer = Depack(append(tmpBuffer, buffer[:n]...), conn, readerChannel)
	}
}

func reader(readerChannel chan Msg) {
	for {
		select {
		case data := <-readerChannel:
			go HandleMessage(data)
		}
	}
}

func Log(v ...interface{}) {
	log.Println(v...)
}
